/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import com.yami.shop.bean.app.dto.UserDeductionFundDto;
import com.yami.shop.bean.app.param.PayParam;
import com.yami.shop.bean.event.PaySuccessOrderEvent;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.payment.WeChatPayment;
import com.yami.shop.payment.dto.GetJsapiServiceDto;
import com.yami.shop.payment.dto.PayParamDto;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.PayService;
import com.yami.shop.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.sql.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lanhai
 */
@RestController
@RequestMapping("/p/order")
@Tag(name = "订单接口")
@AllArgsConstructor
public class PayController {

    private final PayService payService;

    @Autowired
    private WeChatPayment weChatPayment;
    @Autowired
    private UserService userService;

    @Autowired
    private ApplicationEventPublisher publisher;

    /**
     * 支付接口
     */
    @PostMapping("/pay")
    @Operation(summary = "根据订单号进行支付" , description = "根据订单号进行支付")
    public ServerResponseEntity<Void> pay(@RequestBody PayParam payParam) {
        YamiUser user = SecurityUtils.getUser();
        String userId = user.getUserId();


        PayInfoDto payInfo = payService.pay(userId, payParam);
        //payService.paySuccess(payInfo.getPayNo(), ""); 关闭自动支付成功
        return ServerResponseEntity.success();
    }

    /**
     * 普通支付接口
     */
    @PostMapping("/normalPay")
    @Operation(summary = "根据订单号进行支付" , description = "根据订单号进行支付")
    public ServerResponseEntity<Map<String,Object>> normalPay(@RequestBody PayParam payParam) {

        YamiUser user = SecurityUtils.getUser();
        String userId = user.getUserId();
        PayInfoDto pay = payService.pay(userId, payParam);

        Map<String,Object> rmap=new HashMap<>();
        if(new BigDecimal(pay.getPayAmount().toString()).compareTo(BigDecimal.ZERO) > 0){
            if(payParam.getPayType() == 1){
                //微信支付
                String openId = weChatPayment.getOpenId(payParam.getCode());
                GetJsapiServiceDto getJsapiServiceDto = new GetJsapiServiceDto();
                getJsapiServiceDto.setWechatpayMchid(WeChatPayment.wechatpayMchid);
                getJsapiServiceDto.setWechatpayMchserialno(WeChatPayment.wechatpayMchserialno);
                getJsapiServiceDto.setWechatpayPrivatekey(WeChatPayment.wechatpayPrivatekey);
                getJsapiServiceDto.setWechatpayApiv3key(WeChatPayment.wechatpayApiv3key);

                getJsapiServiceDto.setWechatpayAppid(WeChatPayment.wechatpayAppid);
                getJsapiServiceDto.setWechatpayAppsecret(WeChatPayment.wechatpayAppsecret);

                PayParamDto payParamDto=new PayParamDto();
                payParamDto.setMerchantId(WeChatPayment.wechatpayMchid);
                payParamDto.setAppid(WeChatPayment.wechatpayAppid);
                payParamDto.setAmount(new BigDecimal(pay.getPayAmount().toString()));
                payParamDto.setOpenid(openId);
                payParamDto.setDescription(pay.getBody());
                payParamDto.setOutTradeNo(pay.getPayNo());
                payParamDto.setParam(null);

                String wxpay = weChatPayment.pay(payParamDto,getJsapiServiceDto);
                Map payParameter = weChatPayment.getPayParameter(wxpay);

                rmap.put("payType","WeChatPay");
                rmap.put("data",payParameter);
            }
            return ServerResponseEntity.success(rmap);
        }else{
            //订单金额被全部抵扣 -> 直接支付成功
            publisher.publishEvent(new PaySuccessOrderEvent(pay.getPayNo(),""));

            rmap.put("payType","needNotPayment");//无须支付
            rmap.put("data",null);

            return ServerResponseEntity.success(rmap);
        }
        // 根据内部订单号更新order settlement
        //payService.paySuccess(pay.getPayNo(), "");
    }
}
